package com.jml.代理模式.五期.service;


import com.jml.代理模式.五期.service.cglib.CglibMethodInterceptor;
import com.jml.代理模式.五期.service.jdk.JdkInvocationHandler;
import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Enhancer;


public class Client {
    public static void main(String[] args) {
//        OrderService orderService = new OrderServiceProxy();
//        orderService.order();
        // 1.使用jdk动态代理,
        //这行代码就是把当前动态代理类生成到当前类

        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        //不能使用OrderServiceImpl接收，会报错类型转换异常，只能用接口接收
        //新生成的动态代理会继承Proxy类实现OrderService接口
        OrderService proxy = new JdkInvocationHandler(new OrderServiceImpl()).getProxy();
        System.out.println(proxy.getClass().getName());
        proxy.order();

     //java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to com.jml.service.impl.OrderServiceImpl


        // 2.使用cglib动态代理
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\code");
        CglibMethodInterceptor cglibMethodInterceptor = new CglibMethodInterceptor();
        Enhancer enhancer = new Enhancer();
        // 设置代理类的付类
        enhancer.setSuperclass(OrderServiceImpl.class);
        // 设置回调对象
        enhancer.setCallback(cglibMethodInterceptor);
        // 创建代理对象,这里不能用接口去接收，要用实现类取接口，因为生成的代理类，就是继承了实现类作为父类。
        OrderServiceImpl orderServiceImpl = (OrderServiceImpl) enhancer.create();
        orderServiceImpl.order();
    }
}
